package xjtu.sad.zbsj.user.forget;


import xjtu.sad.zbsj.common.MailTool;
import xjtu.sad.zbsj.common.Result;
import xjtu.sad.zbsj.user.login.LoginService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * @RestController = @Controller + @ResponseBody
 * @Controller: 将当前修饰的类注入SpringBoot IOC 容器
 * @ResponseBody: 将修饰的类的返回值转化为Json格式（String类型仍保留String）
 */
@RestController
@RequestMapping("/user/forget")
public class ForgetAPI {

    private static String codeId = "";
    private static String emailAddress = "";

    @Resource
    private ForgetService forgetService;

    @Resource
    private LoginService loginService;

    @RequestMapping("")
    public Result updatePwd(@RequestBody ForgetDto dto){
        dto.setU_pwd(dto.getU_pwd());
        boolean ok = forgetService.checkCount(dto);//等于1说明账号存在
        if(ok){
            forgetService.updatePwd(dto);
            return Result.success("修改密码成功");
        }
        else{
            return Result.fail(Result.ERR_CODE_BUSINESS,"用户不存在");
        }

    }

    @RequestMapping("/getCode")
    @ResponseBody
    public Result getCode(String email , HttpServletRequest request){
        //随机生成一个验证码
        Integer code=new Random().nextInt(999999);
        //request.getSession().setAttribute("code",code.toString());
        //request.getSession().setAttribute("email",email);

        codeId = code.toString();
        emailAddress = email;

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        MailTool.send(email,code);
                    }
                }
        ).start();
        return Result.success("success");
    }

    @RequestMapping("/updatePwd")
    public Result updatePwd(String email , String code, HttpServletRequest request){
        //String emailAddress = (String) request.getSession().getAttribute("email");
        //String codeId = (String) request.getSession().getAttribute("code");
        System.out.println("+++++++++++++"+ code )  ;
        if (email.equals(emailAddress) && code.equals(codeId)){
            System.out.println("邮箱密码匹配成功");
            return Result.success("success");
        }else {
            return Result.fail(Result.ERR_CODE_BUSINESS, "验证码错误！");
        }
    }

}
